import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { getToken } from '@/utils/auth';

interface AuthRouteProps {
  children: React.ReactElement;
  permissions?: string[]; // 该路由需要的权限
}

const AuthRoute: React.FC<AuthRouteProps> = ({ children, permissions = [] }) => {
  const token = getToken();
  const location = useLocation();
  const userPermissions = JSON.parse(localStorage.getItem('userPermissions') || '[]');

  // 判断是否登录
  if (!token) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  // 判断是否有权限
  const hasPermission = permissions.length === 0 ||
    permissions.some(permission => userPermissions.includes(permission));

  if (!hasPermission) {
    return <Navigate to="/403" replace />;
  }

  return children;
};

export default AuthRoute;
